﻿using System;
using USNetFramework.Utils;

namespace Crypt.Common
{
    public class Des
    {
        /// 获取Des32位密钥
        /// </summary>
        /// <param name="key">Des密钥字符串</param>
        /// <returns>Des64位密钥</returns>
        public static byte[] CheckDesKey(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key", "Des密钥不能为空");
            }
            if (key.Length < 8)
            {
                // 不足32补全
                key = key.PadRight(8, '0');
            }
            if (key.Length > 8)
            {
                key = key.Substring(0, 8);
            }
            return System.Text.Encoding.UTF8.GetBytes(key);
        }

        ///<summary>
        ///加密
        ///</summary>
        ///<param name="toEncrypt">需要被加密的数据</param>
        ///<param name="inKey">加密秘钥</param>
        ///<returns></returns>
        public static byte[] Encrypt(byte[] toEncrypt, string inKey)
        {
            Byte[] keyArray = CheckDesKey(inKey);

            return Encrypt(toEncrypt, inKey);
        }

        ///<summary>
        ///加密
        ///</summary>
        ///<param name="toEncrypt">需要被加密的数据</param>
        ///<param name="inKey">加密秘钥</param>
        ///<returns></returns>
        public static byte[] Encrypt(byte[] toEncrypt, byte[] inKey)
        {
            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
            des.Key = inKey;
            des.IV = inKey;

            System.Security.Cryptography.ICryptoTransform transform = des.CreateEncryptor();
            Byte[] resultArray = transform.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);

            return resultArray;
        }

        ///<summary>
        ///解密
        ///</summary>
        ///<param name="toDecrypt">需要被解密的数据</param>
        ///<param name="inKey">加密秘钥</param>
        ///<returns></returns>
        public static byte[] Decrypt(byte[] toDecrypt, string inKey)
        {
            Byte[] keyArray = CheckDesKey(inKey);

            return Decrypt(toDecrypt, keyArray);
        }

        ///<summary>
        ///解密
        ///</summary>
        ///<param name="toDecrypt">需要被解密的数据</param>
        ///<param name="inKey">加密秘钥</param>
        ///<returns></returns>
        public static byte[] Decrypt(byte[] toDecrypt, byte[] inKey)
        {
            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
            des.Key = inKey;
            des.IV = inKey;

            System.Security.Cryptography.ICryptoTransform transform = des.CreateDecryptor();
            Byte[] resultArray = transform.TransformFinalBlock(toDecrypt, 0, toDecrypt.Length);

            return resultArray;
        }
}
}